package com.crm.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.crm.base.model.BaseModel;
import com.crm.sys.model.Log;
import com.crm.sys.service.SysService;
import com.crm.user.model.UserAccount;
import com.crm.user.service.UserService;
import com.crm.util.Authorization;
import com.crm.util.Blowfish;
import com.crm.util.Constants;


public class BaseController {
	@Autowired  
	public  HttpServletRequest request;
	
	@Autowired
	private UserService userService;
	@Autowired
	private SysService sysService;
 
	public static final String REDIRECT = "redirect:";
	
	public static final String MOBILEPATH ="mobile";
	
	protected static Blowfish encoder=new Blowfish("jywpcrm");  //传入密钥
	
	/**
	 * 来源页面作跳转
	 */ 
	public String fromPage;
	/**
     * 提示消息
     */
    public String message;
	
	/**
     * Page size
     */
    public int resultSize;
    
    public int skipToPage=1;
    
    public int pageSize =10;
    
    public int totalPageSize;
 
	public int getResultSize() {
		return resultSize;
	}
	
 
	
	@SuppressWarnings("rawtypes")
	protected void setResultSize(List pagelist) {
		if(pagelist!=null && pagelist.size()>0){
			this.resultSize =((BaseModel)pagelist.get(0)).getTotalResults();
			 totalPageSize= (int)Math.ceil((resultSize+pageSize-1)/pageSize);
		}
	}
	
	 public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 *  返回消息内容
	 * @param type     1 成功消息  2错误消息  3 警告消息 4 普通消息
	 * @param msg
	 */
	public void putMsg(int type,String msg){
		request.setAttribute("msgType", type);
		request.setAttribute("msgContent", msg);
	}
	
	/**
	 *  返回消息内容
	 * @param type    1 成功消息  2错误消息  3 警告消息 4 普通消息
	 * @param msg
	 */
	public void putRedirectMsg(int type,String msg,RedirectAttributes attr){
		attr.addFlashAttribute("msgType", type);
		attr.addFlashAttribute("msgContent", msg);
	}
	
	public int getSkipToPage() {
		try{
			skipToPage  = Integer.parseInt(request.getParameter("skipToPage"));
		}catch(Exception e){
			skipToPage=1;
		}
		return skipToPage;
	}

	public void setSkipToPage(int skipToPage) {
		this.skipToPage = skipToPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPageSize() {
		return totalPageSize;
	}

	public void setTotalPageSize(int totalPageSize) {
		this.totalPageSize = totalPageSize;
	}

	public String getFromPage() {
		return fromPage;
	}

	public void setFromPage(String fromPage) {
		this.fromPage = fromPage;
	}
	
	public  HttpSession  getSession(){
		return request.getSession();
	}

	public void write(HttpServletResponse response,String msg){
		try {
			response.getWriter().write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	 public String getIpAddress(){
	    	String ip = request.getHeader("x-forwarded-for");    
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	            ip = request.getHeader("Proxy-Client-IP");    
	        }    
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	            ip = request.getHeader("WL-Proxy-Client-IP");    
	        }    
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	           ip = request.getRemoteAddr();    
	        } 
	        return ip;
	}
	
	protected String getIP(HttpServletRequest request) {
   	String ip = request.getHeader("x-forwarded-for");    
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
           ip = request.getHeader("Proxy-Client-IP");    
       }    
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
           ip = request.getHeader("WL-Proxy-Client-IP");    
       }    
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
          ip = request.getRemoteAddr();    
       } 
       return ip;
	}
	
	

	// \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),    
    // 字符串在编译时会被转码一次,所以是 "\\b"    
    // \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)    
    static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"    
            +"|windows (phone|ce)|blackberry"    
            +"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"    
            +"|laystation portable)|nokia|fennec|htc[-_]"    
            +"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";    
    static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"    
            +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";    
      
    //移动设备正则匹配：手机端、平板  
    static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);    
    static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);    
        
    /** 
     * 检测是否是移动设备访问 
     *  
     * @Title: check  
     * @param userAgent 浏览器标识 
     * @return true:移动设备接入，false:pc端接入 
     */  
    public static String check(HttpServletRequest request){    
    	  boolean isFromMobile=false;  
    	  //String tag  = request.getParameter("mobiletag");
    	  HttpSession session= request.getSession();  
    	 String temp ="/";//默认模板
        try{   
        	String sername = request.getServerName();
        	if(sername.indexOf("m.")>-1){
		    	isFromMobile = true; 
            	temp ="mobile/";
                session.setAttribute("ismbl","mobile");  
		    }else{
		    	 //获取ua，用来判断是否为移动端访问  
                String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();    
                if(null == userAgent){    
                    userAgent = "";    
                }  
                // 匹配    
                Matcher matcherPhone = phonePat.matcher(userAgent);    
                Matcher matcherTable = tablePat.matcher(userAgent); 
                //判断是否为移动端访问  
                if(matcherPhone.find() || matcherTable.find()){    
                	isFromMobile = true; 
                	temp ="mobile/";
                    session.setAttribute("ismbl","mobile");  
                } else {    
                	isFromMobile = false;    
                	session.setAttribute("ismbl","");  
                } 
		    }  
         
        }catch(Exception e){}  
    	 return temp;
    }  
 

	/**
	 * 保存登录用户
	 * */
	protected void setLoginUser(UserAccount u,HttpServletResponse response) {
		if(u.getInfo()!=null&&StringUtils.isNotEmpty(u.getInfo().getPhoto())){
			u.getInfo().setAvatar(u.getInfo().getPhoto());
		}
		request.getSession().setAttribute("user",u);
		//加入cookie
		String idStr = encoder.encryptString(String.valueOf(u.getId()));
		addCookie("u", idStr,response);
		Log log = new Log();
		log.setDescription(getIpAddress());
		log.setUid(getLoginUser().getId());
		log.setCreateuser(log.getUid());
		log.setState(Constants.LOGSTATE.SIX);
	     sysService.insertLog(log);
		 
	}
	
	
	
	/**
     * 取得登录用户
     * @return
     */
     public UserAccount getLoginUser(){
    	 UserAccount user=null;
    	 try {
    		 //验证授权是否过期
    	 	 boolean b = Authorization.isOutOfTime();
    	 	 if (!b){
 				//过期
 				 return user;
    	 	 }
    	 }catch(Exception e) {
    	 }
   
    	 
    	 user = (UserAccount)request.getSession().getAttribute("user");
    	if(null==user){
    		String idStr = getCookie("u");
    		if(null!=idStr){
    			try{
    				long userId=Long.parseLong(encoder.decryptString(idStr));   //解密
    	    		user=userService.getUserAccountInfoById(userId);
    	    		if(user!=null)
    	    		request.getSession().setAttribute("user", user); 
    			}catch(Exception e){
    			}
    		}
    	} 
    	return user;
     } 
     
     /**
      * 移除用户
      * */
     public void removeUser(HttpServletResponse response){
    	 removeCookie("u",response);
    	 request.getSession().setAttribute("user",null);
    	 request.getSession().setAttribute("userlogout",1);
    	 request.getSession().removeAttribute("user");
     }

	 /**
    * 存放Cookie
    * @param name
    * @param value
    */
   public void addCookie(String name,String value,HttpServletResponse response){
       Cookie cookie = new Cookie(name, value);
       cookie.setMaxAge(60*60*24);
       cookie.setPath("/");
       response.addCookie(cookie);
   }
   
   /**
    * 删除Cookie
    * @param name
    * @param value
    */
   public void removeCookie(String name,HttpServletResponse response){
       Cookie cookie = new Cookie(name, null);
       cookie.setMaxAge(0);
       cookie.setPath("/");
       response.addCookie(cookie);
   }
   
   /**
    * Cookie取得
    * @return
    * @throws Exception
    */
   public String getCookie(String name){
     try{
   	  Cookie[] cookies = request.getCookies();
         for(Cookie cookie : cookies){
       	  cookie.setPath("/");
 	        if(cookie.getName().equals(name)){
 	            return cookie.getValue();
 	        }
         }
     }catch(Exception e){  }
     return "";
   }
   
   /**
    * 返回到错误界面
    * @return
    */
   public String toErrorPage(String errorMessage,HttpServletResponse response) throws Exception
   {
   	PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");
		out.println(errorMessage);
		out.close();
		return "/page/error.jsp";
   }
   
   /**
    * 返回到成功/失败的页面(并带有弹出框提示信息)
    * @param message 提示信息
    * @param destinationPage 跳转到的目标页面
    * @return
    */
   public String toSpecificPage(String message , String destinationPage,HttpServletResponse response)
   {   
   	PrintWriter out = null;
   	try
   	{
   	  out = response.getWriter();
   	}catch(Exception e)
   	{
   		e.printStackTrace();
   	}
		 response.setContentType("text/html;charset=UTF-8");
   	 out.println("<script language=\"javascript\">");
		 out.println("alert('"+message+"!');");
		 out.println("location.href='/"+destinationPage+"'");
		 out.println("</script>");
		 out.close();
		 return null;
   }
   
   public String toLoginPage(String message,HttpServletResponse response) throws Exception
   {
   	PrintWriter out = null;
   	try
   	{
   	  out = response.getWriter();
   	}catch(Exception e)
   	{
   		e.printStackTrace();
   	}
		response.setContentType("text/html;charset=UTF-8");
       out.print(message);
		out.close();
		 return "/page/moblie/user";
   }
   
 
	
	
}
